<template>
  <el-button type="primary" @click="popupUserAdd = true">
  <el-icon><DocumentAdd /></el-icon>
    用户
  </el-button>

  <el-table :data="tableData" v-loading="loading" style="width: 100%">
    <el-table-column prop="name" label="名称" width="180" />
    <el-table-column prop="alias" label="别名" width="180" />
    <el-table-column prop="password" label="密码" />
    
    <el-table-column label="操作" width="280" fixed="right">
      <template #default="scope">
        <el-icon @click="updateUser(scope.row)"><Edit /></el-icon>
        <el-icon @click="deleteUser(scope.row)"><Delete /></el-icon>
        <el-icon @click=""><Delete /></el-icon>
        <el-icon @click=""><Delete /></el-icon>
      </template>
    </el-table-column>

  </el-table>
  <UserAdd v-model="popupUserAdd" @success="refresh"></UserAdd>
  <UserUpdate v-model="popupUserUpdate" :userData="currentUser" @success="refresh"></UserUpdate>
</template>

<script setup name="UserView">
import {ref, onMounted, toRaw} from 'vue'
import apiUser from '@/api/system/user'
import UserAdd from '@/components/Popup/User/UserAdd.vue'
import UserUpdate from '@/components/Popup/User/UserUpdate.vue'
import {ElMessageBox, ElNotification} from 'element-plus'

const popupUserAdd = ref(false)
const popupUserUpdate = ref(false)

const tableData = ref(null)
const searchQuery = ref('')
const loading = ref(true)
const currentUser=ref({})

// 获取表格数据
const fetchTableData = async () => {
  try {
    const params = { q: searchQuery.value }
    const response = await apiUser.getUsers(params)
    tableData.value = response.data || []
  } catch (error) {
    console.error('获取数据失败:', error)
  }
  finally {
    loading.value = false
  }
}

const updateUser = (row) => {
  currentUser.value = toRaw(row)
  popupUserUpdate.value = true
}

const deleteUser = (row) => {
  ElMessageBox.confirm(
    '是否删除用户?', 
    '删除',
    {
      confirmButtonText: '确认',
      cancelButtonText: "取消",
      type: 'warning'
    }).then(() => {
      apiUser.deleteUser(row.id)
      ElNotification({message: "删除成功", type: 'success'})
      
      refresh()
    }).catch(() => {
      console.log('cancel')
    })
}

// 初始化获取数据
onMounted(() => {
  fetchTableData()
})

const refresh = () => {
  loading.value = true
  fetchTableData()
  loading.value = false
}
</script>
